//
//  HMInfomationController.m
//  HeartMark
//
//  Created by rimi on 16/11/9.
//  Copyright © 2016年 黄华强. All rights reserved.
//

#import "HMInfomationController.h"
#import <Masonry.h>
#import <AVOSCloud/AVOSCloud.h>
#import "HMLoginController.h"
#import "HMAlertView.h"

@interface HMInfomationController ()<UITextFieldDelegate>

@property(nonatomic,strong)UITextField* emailT;
@property(nonatomic,strong)UITextField* phoneT;
@property (nonatomic,strong) UIButton* emailValidationBtn;

@property (nonatomic, strong) UITextField *userNameTF;


@end


@implementation HMInfomationController

- (void)viewDidLoad {
    [super viewDidLoad];
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    [self setupUI];
}


#pragma mark --UI
- (void)setupUI {
    self.view.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    
    UIView *userView = [[UIView alloc] initWithFrame:CGRectMake(0, 80, SCREEN_WIDTH, 44)];
    userView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:userView];
    
    UILabel *nickNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, SCREEN_WIDTH * 0.2, 44)];
    nickNameLabel.text = @"用户昵称";
    nickNameLabel.font = [UIFont systemFontOfSize:SCREEN_WIDTH * 0.04];
    [userView addSubview:nickNameLabel];
    
    _userNameTF = [[UITextField alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 0.22, 4, SCREEN_WIDTH  * 0.58, 36)];
    _userNameTF.delegate = self;
    [_userNameTF setBorderStyle:UITextBorderStyleRoundedRect];
    _userNameTF.font = [UIFont systemFontOfSize:SCREEN_WIDTH * 0.04];
    _userNameTF.placeholder = @"请输入用户昵称";
    _userNameTF.text = self.userName;
    [userView addSubview:_userNameTF];
    
    UIButton *changeNickNameBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 0.82, 4, SCREEN_WIDTH * 0.15, 36)];
    changeNickNameBtn.backgroundColor = [UIColor blueColor];
    changeNickNameBtn.titleLabel.font = [UIFont systemFontOfSize:SCREEN_WIDTH * 0.04];
    [changeNickNameBtn setTitle:@"修改" forState:(UIControlStateNormal)];
    changeNickNameBtn.layer.borderWidth = 0.5;
    [changeNickNameBtn addTarget:self action:@selector(rightItemClicked) forControlEvents:(UIControlEventTouchUpInside)];
    [userView addSubview:changeNickNameBtn];
    
    
    
    UIView* emailVc = [[UIView alloc] initWithFrame:CGRectMake(0, 130, SCREEN_WIDTH, 44)];
    emailVc.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:emailVc];
    
    UIImageView* emailImage = [[UIImageView alloc] initWithFrame:CGRectMake(8, 8, 28, 28)];
    emailImage.image = [UIImage imageNamed:@"邮箱"];
    [emailVc addSubview:emailImage];
    
    UILabel* emailL = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, SCREEN_WIDTH * 0.22 - 40, 44)];
    emailL.text = @"邮箱";
    emailL.font = [UIFont systemFontOfSize:SCREEN_WIDTH * 0.04];
    [emailVc addSubview:emailL];
    
    
    _emailT = [[UITextField alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 0.22, 4, SCREEN_WIDTH * 0.58, 36)];
    [_emailT setBorderStyle:UITextBorderStyleRoundedRect];
    _emailT.font = [UIFont systemFontOfSize:SCREEN_WIDTH * 0.04];
    [emailVc addSubview:_emailT];
    
    //邮箱验证按钮
    _emailValidationBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 0.82, 4, SCREEN_WIDTH * 0.15, 36)];
    
    
    _emailValidationBtn.titleLabel.font = [UIFont systemFontOfSize:SCREEN_WIDTH * 0.04];
    _emailValidationBtn.layer.borderWidth = 0.5;
 
    [_emailValidationBtn addTarget:self action:@selector(validationBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [emailVc addSubview:_emailValidationBtn];
    
    UIButton *exitBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 0.2, SCREEN_HEIGHT * 0.4, SCREEN_WIDTH * 0.6, 44)];
    [exitBtn setTitle:@"切换账号" forState:UIControlStateNormal];
    exitBtn.backgroundColor = [UIColor blueColor];
    exitBtn.layer.cornerRadius = 5;
    [exitBtn addTarget:self action:@selector(exitBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:exitBtn];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    AVUser* currentUser = [AVUser currentUser];
    
    if (currentUser.email) {
        _emailT.text = currentUser.email;
    } else {
        _emailT.placeholder = @"请输入你的验证邮箱";
    }
    
    
    AVQuery *query = [AVQuery queryWithClassName:@"_User"];
    [query whereKey:@"objectId" equalTo:currentUser[@"objectId"]];
    [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
        if (error) {
            
        } else {
        
        AVUser *user = objects.firstObject;
        NSInteger emailNumber = [user[@"emailVerified"] integerValue];
        
        
        if (emailNumber == 1) {
            
            _emailT.userInteractionEnabled = NO;
            
            [_emailValidationBtn setTitle:@"已验证" forState:UIControlStateNormal];
            [_emailValidationBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            _emailValidationBtn.layer.borderColor = [UIColor grayColor].CGColor;
            _emailValidationBtn.userInteractionEnabled = NO;
            
        }else{
            
            _emailT.userInteractionEnabled = YES;
            [_emailValidationBtn setTitle:@"验证" forState:UIControlStateNormal];
            [_emailValidationBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            _emailValidationBtn.layer.borderColor = [UIColor redColor].CGColor;
        }
        
        }
        
    }];
        
}

- (void)exitBtnClicked {
    
    UIAlertController *aleraVc = [UIAlertController alertControllerWithTitle:@"确定退出吗" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [AVUser logOut];  //清除缓存用户对象
        HMLoginController *loginVC = [[HMLoginController alloc] init];
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        window.rootViewController = loginVC;
        
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [aleraVc addAction:sureAction];
    [aleraVc addAction:cancelAction];
    [self presentViewController:aleraVc animated:YES completion:nil];
}

#pragma mark --UITextField代理方法

- (void)rightItemClicked {
    if (![_userNameTF.text isEqualToString:@""]) {
        _MyBlock(_userNameTF.text);
    }
    [self.navigationController popViewControllerAnimated:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark --点击屏幕收起键盘


//验证按钮回调事件
-(void)validationBtnClicked:(UIButton*)btn{
    
    
    if ([_emailT.text isEqualToString:@""]) {
        [self setAlertVc:@"验证邮箱不能为空"];
        
    }else{
        AVUser *currentUser = [AVUser currentUser];
        if (currentUser.email && [_emailT.text isEqualToString:currentUser.email]) {
            
            [AVUser requestEmailVerify:currentUser.email withBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    [HMAlertView bottomAlertView:@"发送验证邮件成功，请查看邮箱"];
                }
                if (error.code == 1) {
                    [HMAlertView bottomAlertView:@"已经发送过验证邮件了，请查看邮箱"];
                }
                if (error.code == 203) {
                    [HMAlertView bottomAlertView:@"此邮箱已经被其他账号验证了"];
                }
            }];
            
            
            
        } else {
            
            [currentUser setObject:_emailT.text forKey:@"email"];
            [currentUser saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                if (succeeded) {
                    [AVUser requestEmailVerify:_emailT.text withBlock:^(BOOL succeeded, NSError *error) {
                        if (succeeded) {
                            [HMAlertView bottomAlertView:@"发送验证邮件成功，请查看邮件"];
                        } else {
                            if (error.code == 203) {
                                [HMAlertView bottomAlertView:@"此邮箱已经被其他账号验证，请考虑使用你以前注册的账号登录"];
                            } else {
                                [HMAlertView bottomAlertView:@"发送邮件出现问题"];
                            }
                        }
                        
                    }];
                }
            }];
            
            
        }
    }
    
    
}
//提示框
-(void)setAlertVc:(NSString*)string{
    UIAlertController* alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleAlert];
    
    [alertVc addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }]];
    
    [self presentViewController:alertVc animated:YES completion:nil];
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    
    [self.view endEditing:YES];
}

@end
